﻿using System.Web;
using System.Web.Routing;
using Sissonix.ExtRest.Processors;
using Sissonix.ExtRest.Configuration;
using Sissonix.ExtRest.WADL;

namespace Sissonix.ExtRest
{
    /// <summary>
    /// Reroutes requests to RestHandler.
    /// </summary>
    public class RestRouteHandler : IRouteHandler
    {
        /// <summary>
        /// Gets the name of the service.
        /// </summary>
        /// <value>The name of the service.</value>
        public string ServiceName { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="RestRouteHandler"/> class.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        public RestRouteHandler(string serviceName)
        {
            ServiceName = serviceName;
        }

        /// <summary>
        /// Provides the object that processes the request.
        /// </summary>
        /// <param name="requestContext">An object that encapsulates information about the request.</param>
        /// <returns>An object that processes the request.</returns>
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new MasterProcessor();
        }


        /// <summary>
        /// This static method should be added to the Global.asax
        /// Application_Start() method to make sure that the proper
        /// listeners are added to the route table.
        /// It is add like this:
        ///   ExtRestConfig.AppStart();
        /// </summary>
        public static void AppStart()
        {
            WADLManager.Singleton.LoadWADL(ExtRestConfig.Singleton.WADLRelativePath);
            application app = WADLManager.Singleton.Application;
            resources rr;
            for (int a = 0; a < app.resources.Length; a++)
            {
                rr = app.resources[a];
                var route = new System.Web.Routing.Route(rr.@base + "/{*path}",
                    new ExtRest.RestRouteHandler(rr.@base));
                System.Web.Routing.RouteTable.Routes.Add(route);
            }
        }


    }
}
